package com.slipper.gen.util;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import com.slipper.gen.entity.ColumnEntity;
import com.slipper.gen.entity.TableEntity;

import java.io.File;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class GenUtil {
    
    public static List<String> getTemplates(){
        List<String> templates = new ArrayList<>();
        templates.add("template/BO.java.vm");
        templates.add("template/Dao.java.vm");
        templates.add("template/Dao.xml.vm");
        templates.add("template/Sv.java.vm");
        templates.add("template/SvImpl.java.vm");
        templates.add("template/Service.java.vm");
        templates.add("template/Controller.java.vm");
        templates.add("template/sql.vm");
        templates.add("template/vue.full.vm");
        templates.add("template/vue.middle.vm");
        templates.add("template/vue.simple.vm");
        return templates;
    }
    
    /**
     * 生成代码
     */
    public static void generatorCode(Map<String, String> table, String tablePrefix,
            List<Map<String, Object>> columns, ZipOutputStream zip){
        //配置信息
        Configuration config = getConfig();

        TableEntity tableEntity = new TableEntity();
        tableEntity.setTableName(table.get("tableName"));
        tableEntity.setComments(table.get("tableComment"));
        //表名转换成Java类名
        String className = tableToJava(tableEntity.getTableName(), tablePrefix);
        tableEntity.setClassName(className);
        tableEntity.setClassname(StringUtils.uncapitalize(className));

        boolean hasDeleteFlag = false;
        boolean hasBigDecimal = false;
        List<ColumnEntity> columsList = new ArrayList<>();
        for(Map<String, Object> column : columns){
            ColumnEntity columnEntity = new ColumnEntity();
            columnEntity.setColumnName(column.get("columnName").toString());
            columnEntity.setColumnSize(column.get("columnSize") == null
                    ? -1 : Long.parseLong(column.get("columnSize").toString()));
            columnEntity.setDataType(column.get("dataType").toString());
            String comments = column.get("columnComment").toString();
            columnEntity.setComments(comments
                    .replaceAll("\r\n", "")
                    .replaceAll("\r", "")
                    .replaceAll("\n", "")
                    .replaceAll(" +", " "));
            columnEntity.setExtra(column.get("extra").toString());
            
            String attrName = columnToJava(columnEntity.getColumnName());
            columnEntity.setAttrName(attrName);
            columnEntity.setAttrname(StringUtils.uncapitalize(attrName));
            
            //列的数据类型，转换成Java类型
            String attrType = config.getString(columnEntity.getDataType(), "unknownType");
            columnEntity.setAttrType(attrType);

            if("PRI".equalsIgnoreCase(column.get("columnKey").toString()) && tableEntity.getPk() == null){
                tableEntity.setPk(columnEntity);
            }
            if("delete_flag".equalsIgnoreCase(column.get("columnName").toString())){
                hasDeleteFlag = true;
            }
            if("decimal".equalsIgnoreCase(column.get("dataType").toString())){
                hasBigDecimal = true;
            }
            
            columsList.add(columnEntity);
        }
        tableEntity.setColumns(columsList);
        
        if(tableEntity.getPk() == null){
            tableEntity.setPk(tableEntity.getColumns().get(0));
        }
        
        Properties prop = new Properties();  
        prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");  
        Velocity.init(prop);

        String classPath = (className.substring(0, 1).toLowerCase() + className.substring(1)).split("[A-Z]", 2)[0];

        //封装模板数据
        Map<String, Object> map = new HashMap<>();
        tableEntity.fillProp(map);
        map.put("classPath", classPath);
        map.put("hasDeleteFlag", hasDeleteFlag);
        map.put("hasBigDecimal", hasBigDecimal);
        map.put("package", config.getString("package"));
        map.put("author", config.getString("author"));
        map.put("email", config.getString("email"));
        map.put("schema", config.getString("schema"));
        map.put("datetime", format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        VelocityContext context = new VelocityContext(map);
        
        //获取模板列表
        List<String> templates = getTemplates();
        for(String template : templates){
            //渲染模板
            try {
                StringWriter sw = new StringWriter();
                Template tpl = Velocity.getTemplate(template, "UTF-8");
                tpl.merge(context, sw);
            
                //添加到zip
                zip.putNextEntry(new ZipEntry(getFileName(template, classPath, tableEntity.getClassName())));
                IOUtils.write(sw.toString(), zip, "UTF-8");
                IOUtils.closeQuietly(sw);
                zip.closeEntry();
            } catch (Exception e) {
                throw new RuntimeException("渲染模板失败，模板：" + template + "，表名：" + tableEntity.getTableName(), e);
            }
        }
    }

    public static String columnToJava(String columnName) {
        return WordUtils.capitalizeFully(columnName, new char[]{'_'}).replace("_", "");
    }
    
    /**
     * 表名转换成Java类名
     */
    public static String tableToJava(String tableName, String tablePrefix) {
        if(StringUtils.isNotBlank(tablePrefix)){
            tableName = tableName.replaceFirst(tablePrefix, "");
        }
        return columnToJava(tableName);
    }
    
    /**
     * 获取配置信息
     */
    public static Configuration getConfig(){
        try {
            return new PropertiesConfiguration("generator.properties");
        } catch (ConfigurationException e) {
            throw new RuntimeException("获取配置失败", e);
        }
    }

    public static String getFileName(String template, String classPath, String className){
        String packagePath = "/";
        if(template.contains("BO.java.vm")){
            return packagePath
                    + "api/" + classPath + File.separator
                    + "bo" + File.separator
                    + className + "BO.java";
        }
        if(template.contains("Sv.java.vm")){
            return packagePath + "api/" + classPath + File.separator
                    + "service" + File.separator + "I" + className + "Sv.java";
        }
        if(template.contains("Dao.java.vm")){
            return packagePath + "service/" + classPath + File.separator
                    + "dao" + File.separator + className + "Dao.java";
        }
        if(template.contains("Dao.xml.vm")){
            return packagePath + "service/" + classPath + File.separator
                    + "dao" + File.separator + className + "Dao.xml";
        }
        if(template.contains("SvImpl.java.vm")){
            return packagePath + "service/" + classPath + File.separator
                    + "front" + File.separator + File.separator + className + "Sv.java";
        }
        if(template.contains("Service.java.vm")){
            return packagePath + "service/" + classPath + File.separator
                    + "service" + File.separator + File.separator + className + "Service.java";
        }
        if(template.contains("Controller.java.vm")){
            return packagePath + "controller/" + classPath + File.separator + className + "Controller.java";
        }
        String fileName = className.substring(0, 1).toLowerCase() + className.substring(1);
        if(template.contains("sql.vm")){
            return packagePath  + "sql/" + fileName + ".sql";
        }
        if(template.contains("vue.full.vm")){
            return packagePath  + "vue/" + classPath + File.separator + fileName + ".full.vue";
        }
        if(template.contains("vue.middle.vm")){
            return packagePath  + "vue/" + classPath + File.separator + fileName + ".middle.vue";
        }
        if(template.contains("vue.simple.vm")){
            return packagePath  + "vue/" + classPath + File.separator + fileName + ".simple.vue";
        }
        
        return packagePath + "unknown/";
    }
    
    public static String format(Date date, String pattern) {
        if(date != null){
            SimpleDateFormat df = new SimpleDateFormat(pattern);
            return df.format(date);
        }
        return null;
    }
}
